<template>
  <div class="login-container">
    <h2>Login</h2>
    <el-form :model="form" :rules="rules" ref="formRef" @submit.prevent="submitForm" label-width="100px" label-align="left">
      <el-form-item label="用户名" prop="username" >
        <el-input v-model="form.username" class="input-box"/>
      </el-form-item>
      <el-form-item label="密码" prop="password" >
        <el-input type="password" v-model="form.password" class="input-box"/>
      </el-form-item>
      <el-button type="primary" native-type="submit">Login</el-button>
    </el-form>
  </div>
</template>
  
<script setup lang="ts">
import {useUserStore}from '../stores/userStore';
import { reactive,ref } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus'

const formRef = ref();
const userStore = useUserStore();
const router = useRouter();

const form = reactive({
  username: '',
  password: ''
})

const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 12, message: '长度在3到12个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ]
})


const submitForm = async () => {
  try {
    // 先进行表单验证
    await formRef.value.validate()
    await userStore.login(form);
    router.push('/home');
  } catch (error) {
    console.error('Login failed', error);
    ElMessage.error('登录失败，请检查输入信息')
  }
};
</script>

<style scoped>
.login-container {
  max-width: 400px;
  margin: 50px auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.input-box {
  width: 100%; /* 确保输入框宽度一致 */
}


</style>